package top.wsuo.controller;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import top.wsuo.factory.ServiceFactory;
import top.wsuo.model.User;

@WebServlet("/user/login.do")
public class UserLoginAction extends HttpServlet {

    /**
     * 登陆接口
     *
     * @param request  请求对象
     * @param response 响应对象
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        // 初始化 session 和 user 对象
        HttpSession session = request.getSession();
        User user;

        // 从前端获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        try {
            // 如果数据库中没有该用户: 登陆失败
            if (ServiceFactory.createUserService().getUser(username) == null) {
                System.out.println("用户" + username + "不存在");
                response.sendRedirect("loginNoUser.jsp");
            } else {
                // 用户存在再判断用户的密码是否正确
                user = ServiceFactory.createUserService().getUser(username);
                System.out.println("用户" + username + "存在");
                if (user.getPassword().equals(password)) {
                    System.out.println("用户：" + username + " 登录成功");
                    // 登陆成功则保存到 session 中
                    session.setAttribute("user", user);
                    response.sendRedirect("loginSucceed.jsp");
                } else {
                    System.out.println("用户：" + username + " 密码错误");
                    response.sendRedirect("loginFailed.jsp");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        doGet(request, response);
    }

}
